<template>
  <div class="room-lobby-container">
    <div class="lobby-header">
      <div class="room-info">
        <h1>房间名称:{{ roomName }}</h1>
        <div class="room-details">
          <span class="room-code">房间代码: {{ roomId }}</span>
          <span class="player-count">玩家: {{ players.length }}/{{ maxPlayers }}</span>
        </div>
      </div>
      
      <div class="header-actions">
        <el-button @click="copyRoomCode" type="info" size="large">
          <el-icon><CopyDocument /></el-icon>
          复制房间代码
        </el-button>
        
        <el-button @click="leaveRoom" type="danger" size="large">
          <el-icon><Close /></el-icon>
          离开房间
        </el-button>
      </div>
    </div>

    <div class="lobby-content">
      <div class="players-section">
        <h2>玩家列表</h2>
        
        <div class="players-grid">
          <div
            v-for="player in players"
            :key="player.id"
            class="player-card"
            :class="{ 'current-player': player.id === currentPlayerId }"
          >
            <div class="player-avatar">
              <div 
                class="avatar-color" 
                :style="{ backgroundColor: player.color }"
              ></div>
              <div v-if="player.isOwner" class="owner-badge">房主</div>
            </div>
            
            <div class="player-info">
              <div class="player-name">{{ player.nickname }}</div>
              <div class="player-status">已准备</div>
            </div>
          </div>
          
          <!-- 空位显示 -->
          <div
            v-for="i in emptySlots"
            :key="`empty-${i}`"
            class="player-card empty-slot"
          >
            <div class="player-avatar">
              <div class="avatar-placeholder">
                <el-icon><User /></el-icon>
              </div>
            </div>
            
            <div class="player-info">
              <div class="player-name">等待加入...</div>
              <div class="player-status">未准备</div>
            </div>
          </div>
        </div>
      </div>

      <div class="game-controls">
        <div class="control-section">
          <h3>游戏设置</h3>
          
          <div class="setting-item">
            <label>游戏时长:</label>
            <el-select v-model="gameDuration" :disabled="!isRoomOwner" @change="onGameSettingChange">
              <el-option label="5秒" :value="5" />
              <el-option label="2分钟" :value="120" />
              <el-option label="3分钟" :value="180" />
              <el-option label="5分钟" :value="300" />
            </el-select>
          </div>
          
          <div class="setting-item">
            <label>画笔大小:</label>
            <el-select v-model="brushSize" :disabled="!isRoomOwner" @change="onGameSettingChange">
              <el-option label="小" :value="8" />
              <el-option label="中" :value="12" />
              <el-option label="大" :value="16" />
            </el-select>
          </div>
          
          <div v-if="isRoomOwner" class="setting-status">
            <el-tag type="success" size="small">
              <el-icon><Check /></el-icon>
              设置已保存
            </el-tag>
          </div>
        </div>

        <div class="action-section">
          <el-button
            v-if="isRoomOwner"
            @click="startGame"
            type="primary"
            size="large"
            :disabled="players.length < 2"
            class="start-button"
          >
            <el-icon><VideoPlay /></el-icon>
            开始游戏
          </el-button>
          
          <div v-else class="waiting-message">
            <el-icon class="waiting-icon"><Clock /></el-icon>
            <p>等待房主开始游戏...</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-section">
      <h3>聊天</h3>
      <div class="chat-messages" ref="chatMessagesRef">
        <div
          v-for="message in chatMessages"
          :key="message.id"
          class="chat-message"
          :class="{ 'own-message': message.PlayerId === currentPlayerId, 'owner-message': isOwnerMessage(message.PlayerId) }"
        >
          <div class="message-header">
            <span class="message-player">
              {{ getPlayerName(message.PlayerId) }}
              <el-tag v-if="isOwnerMessage(message.PlayerId)" type="danger" size="small" class="owner-badge-tag">房主</el-tag>
            </span>
            <span class="message-time">{{ formatTime(message.Timestamp) }}</span>
          </div>
          <div class="message-content">{{ message.Message }}</div>
        </div>
      </div>
      
      <div class="chat-input">
        <el-input
          v-model="chatInput"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
          :disabled="!isConnected"
        >
          <template #append>
            <el-button @click="sendMessage" :disabled="!chatInput.trim()">
              发送
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 连接状态提示 -->
    <el-alert
      v-if="!isConnected"
      title="连接断开"
      type="warning"
      :closable="false"
      show-icon
      class="connection-alert"
    >
      <template #default>
        正在尝试重新连接...
        <el-button @click="reconnect" size="small" style="margin-left: 10px">
          重连
        </el-button>
      </template>
    </el-alert>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  CopyDocument, Close, User, VideoPlay, Clock, Check 
} from '@element-plus/icons-vue'
import { useGameStore } from '@/stores/game'
import { createSignalRService } from '@/services/socketService'

const props = defineProps({
  roomId: {
    type: String,
    required: true
  }
})

const router = useRouter()
const gameStore = useGameStore()
const signalRService = createSignalRService(gameStore)

// 引用
const chatMessagesRef = ref()
let roomInfoInterval = null

// 状态（本地选择框值）
const gameDuration = ref(180)
const brushSize = ref(12)
const chatInput = ref('')
const chatMessages = computed(() => gameStore.chatMessages)

// 计算属性
const roomName = computed(() => {
  // 优先从后端房间信息获取房间名称（兼容大小写）
  const nameFromInfo = gameStore.roomInfo?.RoomName || gameStore.roomInfo?.roomName
  if (nameFromInfo) return nameFromInfo
  // 其次使用当前房间信息中的名称（创建房间后本地已设置）
  const nameFromCurrent = gameStore.currentRoom?.name
  if (nameFromCurrent) return nameFromCurrent
  // 兜底显示房间代码
  return `房间 ${props.roomId}`
})
const maxPlayers = computed(() => {
  const fromRoomInfo = (gameStore.roomInfo && (gameStore.roomInfo.MaxPlayers ?? gameStore.roomInfo.maxPlayers))
  const fromCurrentRoom = gameStore.currentRoom?.maxPlayers
  const max = Number(fromRoomInfo ?? fromCurrentRoom ?? 6)
  return Number.isFinite(max) && max > 0 ? max : 6
})
const players = computed(() => gameStore.players)
const currentPlayerId = computed(() => gameStore.currentPlayer?.id)
const isRoomOwner = computed(() => {
  // 检查当前玩家是否是房主
  return gameStore.currentPlayer?.isOwner || false
})
const isConnected = computed(() => gameStore.isConnected)
const ownerId = computed(() => gameStore.currentRoom?.hostId || gameStore.roomInfo?.OwnerId || gameStore.roomInfo?.ownerId || null)

const emptySlots = computed(() => {
  const empty = maxPlayers.value - players.value.length
  return empty > 0 ? empty : 0
})

// 在组件挂载时初始化SignalR服务
onMounted(() => {
  // 连接到房间
  connectToRoom()
  // 周期性刷新房间信息，确保人数实时
  if (roomInfoInterval) clearInterval(roomInfoInterval)
  roomInfoInterval = setInterval(() => {
    getRoomInfo()
  }, 3000)
  // 页面可见时立即刷新
  document.addEventListener('visibilitychange', handleVisibilityChange)
})

onUnmounted(() => {
  removeRoomListeners()
  if (roomInfoInterval) {
    clearInterval(roomInfoInterval)
    roomInfoInterval = null
  }
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})

// 连接到房间
function connectToRoom() {
  if (!props.roomId) {
    ElMessage.error('房间ID无效')
    return
  }

  try {
    // 初始化房间
    initializeRoom()
    setupRoomListeners()
    
    // 延迟获取房间信息，确保连接建立完成
    setTimeout(() => {
      getRoomInfo()
    }, 1000)
    
    ElMessage.success('已连接到房间')
  } catch (error) {
    ElMessage.error('连接房间失败: ' + error.message)
  }
}

// 同步本地选择框与全局store中的设置（解决下拉框值被清空/不同步问题）
watch(
  () => gameStore.gameDuration,
  (val) => {
    const num = typeof val === 'number' ? val : Number(val)
    if (!Number.isNaN(num)) {
      gameDuration.value = num
    }
  },
  { immediate: true }
)

watch(
  () => gameStore.brushSize,
  (val) => {
    const num = typeof val === 'number' ? val : Number(val)
    if (!Number.isNaN(num)) {
      brushSize.value = num
    }
  },
  { immediate: true }
)

function initializeRoom() {
  // 连接到房间
  signalRService.connect()
  
  // 检查是否已有玩家信息，如果没有则生成新的
  if (!gameStore.currentPlayer) {
    const newPlayer = {
      id: generatePlayerId(),
      nickname: '玩家',
      color: generateRandomColor(),
      isOwner: false
    }
    gameStore.setCurrentPlayer(newPlayer)
    
    // 保存到localStorage
    localStorage.setItem('currentPlayer', JSON.stringify(newPlayer))
    console.log('新玩家信息已保存到localStorage:', newPlayer)
  } else {
    // 更新localStorage中的玩家信息
    localStorage.setItem('currentPlayer', JSON.stringify(gameStore.currentPlayer))
    console.log('现有玩家信息已更新到localStorage:', gameStore.currentPlayer)
  }
  
  // 如果已经在该房间，则避免重复 Join，仅刷新房间信息
  const alreadyInSameRoom = gameStore.currentRoom && gameStore.currentRoom.id === props.roomId
  if (!alreadyInSameRoom) {
    // 加入房间
    signalRService.joinRoom(
      props.roomId, 
      gameStore.currentPlayer.id, 
      gameStore.currentPlayer.nickname,
      gameStore.currentPlayer.color
    )
  } else {
    // 已在房间，直接拉取一次信息
    getRoomInfo()
  }
  
  // 添加系统消息
  addSystemMessage('欢迎来到房间！')
}

function handleVisibilityChange() {
  if (document.visibilityState === 'visible') {
    getRoomInfo()
  }
}

function setupRoomListeners() {
  // 监听房间相关事件
  signalRService.on('PlayerJoined', handlePlayerJoined)
  signalRService.on('PlayerLeft', handlePlayerLeft)
  signalRService.on('GameStarted', handleGameStarted)
  signalRService.on('ChatMessage', handleChatMessage)
  signalRService.on('RoomStateUpdated', handleRoomStateUpdated)
  signalRService.on('GameSettingsUpdated', handleGameSettingsUpdated)

  // 退房/断开也触发刷新，确保人数变化
  signalRService.on('PlayerDisconnected', () => {
    getRoomInfo()
  })
}

function removeRoomListeners() {
  // 移除事件监听器
  signalRService.off('PlayerJoined', handlePlayerJoined)
  signalRService.off('PlayerLeft', handlePlayerLeft)
  signalRService.off('GameStarted', handleGameStarted)
  signalRService.off('ChatMessage', handleChatMessage)
  signalRService.off('RoomStateUpdated', handleRoomStateUpdated)
  signalRService.off('GameSettingsUpdated', handleGameSettingsUpdated)
  signalRService.off('PlayerDisconnected', () => {})
}

function handlePlayerJoined(playerInfo) {
  addSystemMessage(`${playerInfo.nickname} 加入了房间`)
  
  // 如果是第一个玩家，标记为房主
  if (players.value.length === 0) {
    playerInfo.isOwner = true
  }
  
  // 检查是否是当前玩家
  if (playerInfo.PlayerId === gameStore.currentPlayer?.id) {
    gameStore.setCurrentPlayer({
      ...gameStore.currentPlayer,
      isOwner: playerInfo.isOwner
    })
  }
  
  scrollToBottom()
}

function handlePlayerLeft(playerId) {
  const player = players.value.find(p => p.id === playerId)
  if (player) {
    addSystemMessage(`${player.nickname} 离开了房间`)
    
    // 如果离开的是房主，需要转移房主身份
    if (player.isOwner && players.value.length > 1) {
      // 找到下一个玩家作为新房主
      const nextPlayer = players.value.find(p => p.id !== playerId)
      if (nextPlayer) {
        nextPlayer.isOwner = true
        addSystemMessage(`${nextPlayer.nickname} 成为新房主`)
        
        // 如果新房主是当前玩家，更新状态
        if (nextPlayer.id === gameStore.currentPlayer?.id) {
          gameStore.setCurrentPlayer({
            ...gameStore.currentPlayer,
            isOwner: true
          })
        }
      }
    }
    
    scrollToBottom()
  }
  // 主动刷新一次，确保服务端已剔除的玩家从列表移除
  getRoomInfo()
}

function handleGameStarted(gameInfo) {
  addSystemMessage('游戏开始！')
  // 跳转到游戏页面
  router.push(`/game/${props.roomId}`)
}

function handleChatMessage() {
  scrollToBottom()
}

function handleRoomStateUpdated(roomState) {
  console.log('房间状态更新:', roomState)
  console.log('最大玩家数:', roomState.MaxPlayers)
  console.log('当前玩家数:', roomState.PlayerCount)
  // 重要：不要在这里重建并覆盖 roomInfo，交由 socket 层的全局处理
  // 仅追加系统提示信息
  
  const currentCount = (roomState.Players && Array.isArray(roomState.Players)) ? roomState.Players.length : gameStore.players.length
  addSystemMessage(`房间状态已更新，当前玩家数: ${currentCount}`)
}

function handleGameSettingsUpdated(settingsData) {
  console.log('游戏设置已更新:', settingsData)
  
  // 更新本地设置状态
  const rawDuration = (settingsData && settingsData.GameDuration != null)
    ? settingsData.GameDuration
    : (settingsData && settingsData.gameDuration != null ? settingsData.gameDuration : undefined)
  const rawBrush = (settingsData && settingsData.BrushSize != null)
    ? settingsData.BrushSize
    : (settingsData && settingsData.brushSize != null ? settingsData.brushSize : undefined)
  const duration = Number(rawDuration)
  const brush = Number(rawBrush)
  if (!Number.isNaN(duration) && duration > 0) gameDuration.value = duration
  if (!Number.isNaN(brush) && brush > 0) brushSize.value = brush
  // 同步到全局store，确保其他页面/组件也一致
  gameStore.setGameDuration(gameDuration.value)
  gameStore.setBrushSize(brushSize.value)
  
  // 显示设置更新消息
  const durText = (!Number.isNaN(duration) && duration > 0) ? duration : gameDuration.value
  const brushText = (!Number.isNaN(brush) && brush > 0) ? brush : brushSize.value
  addSystemMessage(`房主已更新游戏设置：时长${durText}秒，画笔大小${brushText}px`)
}

function addSystemMessage(content) {
  // 将系统消息也统一进入全局聊天流，便于所有页面统一显示
  gameStore.addChatMessage({
    PlayerId: 'system',
    Message: content,
    Timestamp: Date.now()
  })
}

function sendMessage() {
  if (!chatInput.value.trim() || !isConnected.value) return
  
  // 发送到服务器（服务端会广播 ChatMessage，前端通过 store 同步展示）
  signalRService.sendChatMessage(
    props.roomId,
    currentPlayerId.value,
    chatInput.value.trim()
  )
  chatInput.value = ''
}

function scrollToBottom() {
  nextTick(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
    }
  })
}

// 监听聊天消息变化，自动滚动
watch(chatMessages, () => {
  scrollToBottom()
})

// 根据 PlayerId 显示昵称（自己显示“我”）
function getPlayerName(playerId) {
  if (playerId === currentPlayerId.value) return '我'
  const p = gameStore.players.find(p => p.id === playerId)
  return p?.nickname || playerId
}

function isOwnerMessage(playerId) {
  return ownerId.value && playerId === ownerId.value
}

function copyRoomCode() {
  navigator.clipboard.writeText(props.roomId).then(() => {
    ElMessage.success('房间代码已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

async function leaveRoom() {
  try {
    await ElMessageBox.confirm(
      '确定要离开房间吗？',
      '确认离开',
      {
        confirmButtonText: '离开',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    try {
      // 先离开房间（必须带上 playerId，确保后端正确移除）
      await signalRService.leaveRoom(props.roomId, currentPlayerId.value)
      console.log('已成功离开房间')
    } catch (error) {
      console.warn('离开房间时出现警告:', error)
      // 即使离开房间失败，也继续清理状态
    }
    
    try {
      // 然后断开连接
      await signalRService.disconnect()
      console.log('已断开连接')
    } catch (error) {
      console.warn('断开连接时出现警告:', error)
    }
    
    // 清理状态
    gameStore.clearRoom()
    
    // 返回主页
    router.push('/')
    
  } catch {
    // 用户取消
  }
}

function startGame() {
  if (players.value.length < 2) {
    ElMessage.warning('至少需要2名玩家才能开始游戏')
    return
  }
  
  // 保存游戏设置到store
  gameStore.setGameDuration(gameDuration.value)
  gameStore.setBrushSize(brushSize.value)
  
  // 发送游戏设置到服务器
  signalRService.startGame(props.roomId, {
    gameDuration: gameDuration.value,
    brushSize: brushSize.value
  })
  
  ElMessage.success('游戏设置已保存，正在开始游戏...')
}

function reconnect() {
  signalRService.connect(props.roomId, currentPlayerId.value)
}

function formatTime(timestamp) {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 生成玩家ID
function generatePlayerId() {
  return 'player_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}

// 生成随机颜色
function generateRandomColor() {
  return '#' + Math.floor(Math.random()*16777215).toString(16)
}

function onGameSettingChange() {
  // 当游戏设置改变时，发送更新到服务器
  if (isRoomOwner.value) {
    // 规范为数字，避免 Element Plus 选择框字符串值导致不匹配而清空
    gameDuration.value = Number(gameDuration.value)
    brushSize.value = Number(brushSize.value)
    
    signalRService.updateGameSettings(
      props.roomId,
      currentPlayerId.value,
      Number.isFinite(gameDuration.value) ? Number(gameDuration.value) : 180,
      Number.isFinite(brushSize.value) ? Number(brushSize.value) : 12
    ).then(() => {
      ElMessage.success('游戏设置已更新')
    }).catch((error) => {
      ElMessage.error('更新游戏设置失败: ' + error.message)
    })
  }
}

// 获取房间信息
async function getRoomInfo() {
  try {
    await signalRService.getRoomInfo(props.roomId)
  } catch (error) {
    console.warn('获取房间信息失败:', error)
  }
}
</script>

<style scoped>
.room-lobby-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
}

.lobby-header {
  background: white;
  border-radius: 16px;
  padding: 30px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.room-info h1 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 2rem;
}

.room-details {
  display: flex;
  gap: 20px;
}

.room-code, .player-count {
  background: #f0f0f0;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.lobby-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.players-section {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.players-section h2 {
  margin: 0 0 25px 0;
  color: #333;
  font-size: 1.5rem;
}

.players-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.player-card {
  background: #fafafa;
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.player-card:hover {
  background: #f0f0f0;
  transform: translateY(-2px);
}

.player-card.current-player {
  border-color: #1890ff;
  background: #e6f7ff;
}

.player-card.empty-slot {
  opacity: 0.6;
}

.player-avatar {
  position: relative;
  margin-bottom: 15px;
}

.avatar-color, .avatar-placeholder {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin: 0 auto;
  border: 3px solid white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-placeholder {
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 24px;
}

.owner-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #ff4d4f;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: bold;
}

.player-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.player-status {
  font-size: 12px;
  color: #666;
}

.game-controls {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.control-section {
  margin-bottom: 30px;
}

.control-section h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 1.2rem;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.setting-item label {
  font-weight: 500;
  color: #666;
}

.setting-status {
  text-align: center;
  margin-top: 15px;
  padding: 10px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 8px;
}

.setting-status .el-tag {
  margin: 0 auto;
}

.action-section {
  text-align: center;
}

.start-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: 600;
}

.waiting-message {
  text-align: center;
  color: #666;
}

.waiting-icon {
  font-size: 2rem;
  margin-bottom: 10px;
  color: #faad14;
}

.chat-section {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.chat-section h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 1.2rem;
}

.chat-messages {
  height: 300px;
  overflow-y: auto;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  background: #fafafa;
}

.chat-message {
  margin-bottom: 15px;
  padding: 10px;
  background: white;
  border-radius: 8px;
  border-left: 3px solid #e8e8e8;
}

.chat-message.own-message {
  border-left-color: #1890ff;
  background: #e6f7ff;
}

.chat-message.owner-message {
  border-left-color: #ff4d4f;
}

.owner-badge-tag {
  margin-left: 6px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.message-player {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.message-content {
  color: #666;
  line-height: 1.4;
}

.chat-input {
  display: flex;
  gap: 10px;
}

.connection-alert {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  max-width: 500px;
}

@media (max-width: 768px) {
  .lobby-content {
    grid-template-columns: 1fr;
  }
  
  .lobby-header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .header-actions {
    flex-direction: column;
    width: 100%;
  }
  
  .players-grid {
    grid-template-columns: 1fr;
  }
  
  .room-details {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
